package com.kexio.pay.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import com.kexio.pay.service.PaymentService;
import com.kexio.pay.service.impl.PaymentServiceImpl;

/**
 * 支付服务自动配置
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
@Configuration
@ConditionalOnProperty(prefix = "kexio.pay", name = "enabled", havingValue = "true")
@EnableConfigurationProperties(PaymentProperties.class)
@ComponentScan(basePackages = "com.kexio.pay")
public class PaymentAutoConfiguration {
    
    private static final Logger logger = LoggerFactory.getLogger(PaymentAutoConfiguration.class);
    
    /**
     * 支付服务Bean
     */
    @Bean
    @ConditionalOnMissingBean
    public PaymentService paymentService() {
        logger.info("注册支付服务: PaymentServiceImpl");
        return new PaymentServiceImpl();
    }
    
    /**
     * 支付服务启动日志
     */
    @Bean
    public PaymentStartupLogger paymentStartupLogger(PaymentProperties properties) {
        return new PaymentStartupLogger(properties);
    }
    
    /**
     * 启动日志组件
     */
    public static class PaymentStartupLogger {
        
        private final PaymentProperties properties;
        
        public PaymentStartupLogger(PaymentProperties properties) {
            this.properties = properties;
            logStartupInfo();
        }
        
        private void logStartupInfo() {
            logger.info("========================================");
            logger.info("💳 Kexio Payment Service 启动成功!");
            logger.info("🔧 基础配置:");
            logger.info("   默认提供商: {}", properties.getDefaultProvider());
            logger.info("   支付超时: {}分钟", properties.getPaymentTimeout());
            logger.info("   订单号前缀: {}", properties.getOrderNoPrefix());
            
            logger.info("💰 支付提供商配置:");
            checkWechatConfig();
            checkAlipayConfig();
            checkUnionPayConfig();
            
            logger.info("🔔 回调配置:");
            logger.info("   异步处理: {}", properties.getCallback().isAsyncEnabled() ? "✅ 启用" : "❌ 禁用");
            logger.info("   最大重试: {}次", properties.getCallback().getRetryMaxTimes());
            logger.info("   重试间隔: {}毫秒", properties.getCallback().getRetryInterval());
            logger.info("   回调超时: {}秒", properties.getCallback().getTimeout());
            logger.info("   IP验证: {}", properties.getCallback().isVerifyIp() ? "✅ 启用" : "❌ 禁用");
            
            logger.info("🛡️ 安全配置:");
            logger.info("   签名验证: {}", properties.getSecurity().isVerifySignature() ? "✅ 启用" : "❌ 禁用");
            logger.info("   HTTPS要求: {}", properties.getSecurity().isRequireHttps() ? "✅ 启用" : "❌ 禁用");
            logger.info("   签名算法: {}", properties.getSecurity().getSignAlgorithm());
            
            logger.info("📊 监控配置:");
            logger.info("   监控开关: {}", properties.getMonitor().isEnabled() ? "✅ 启用" : "❌ 禁用");
            if (properties.getMonitor().isEnabled()) {
                logger.info("   慢查询阈值: {}毫秒", properties.getMonitor().getSlowQueryThreshold());
                logger.info("   详细日志: {}", properties.getMonitor().isDetailedLog() ? "✅ 启用" : "❌ 禁用");
                logger.info("   统计窗口: {}分钟", properties.getMonitor().getStatsWindow());
            }
            
            logger.info("🚀 支付服务已就绪!");
            logger.info("========================================");
        }
        
        private void checkWechatConfig() {
            PaymentProperties.WechatConfig wechat = properties.getWechat();
            boolean configured = wechat.getAppId() != null && !wechat.getAppId().trim().isEmpty() &&
                               wechat.getMchId() != null && !wechat.getMchId().trim().isEmpty();
            
            logger.info("   微信支付: {}{}", 
                       configured ? "✅ 已配置" : "❌ 未配置",
                       wechat.isSandbox() ? " (沙箱模式)" : "");
            
            if (configured) {
                logger.info("     - AppId: {}", maskConfig(wechat.getAppId()));
                logger.info("     - 商户号: {}", maskConfig(wechat.getMchId()));
                logger.info("     - 回调地址: {}", wechat.getNotifyUrl());
            }
        }
        
        private void checkAlipayConfig() {
            PaymentProperties.AlipayConfig alipay = properties.getAlipay();
            boolean configured = alipay.getAppId() != null && !alipay.getAppId().trim().isEmpty() &&
                               alipay.getPrivateKey() != null && !alipay.getPrivateKey().trim().isEmpty();
            
            logger.info("   支付宝: {}{}", 
                       configured ? "✅ 已配置" : "❌ 未配置",
                       alipay.isSandbox() ? " (沙箱模式)" : "");
            
            if (configured) {
                logger.info("     - AppId: {}", maskConfig(alipay.getAppId()));
                logger.info("     - 签名类型: {}", alipay.getSignType());
                logger.info("     - 回调地址: {}", alipay.getNotifyUrl());
            }
        }
        
        private void checkUnionPayConfig() {
            PaymentProperties.UnionPayConfig unionpay = properties.getUnionpay();
            boolean configured = unionpay.getMerId() != null && !unionpay.getMerId().trim().isEmpty() &&
                               unionpay.getCertPath() != null && !unionpay.getCertPath().trim().isEmpty();
            
            logger.info("   银联支付: {}{}", 
                       configured ? "✅ 已配置" : "❌ 未配置",
                       unionpay.isSandbox() ? " (沙箱模式)" : "");
            
            if (configured) {
                logger.info("     - 商户号: {}", maskConfig(unionpay.getMerId()));
                logger.info("     - 证书路径: {}", unionpay.getCertPath());
                logger.info("     - 回调地址: {}", unionpay.getNotifyUrl());
            }
        }
        
        /**
         * 掩码配置信息
         */
        private String maskConfig(String config) {
            if (config == null || config.length() <= 4) {
                return "***";
            }
            return config.substring(0, 4) + "***" + config.substring(config.length() - 2);
        }
    }
}
